<template>
  <div class="home">
    <div class="form-group">
      <label for="exampleInputFile">选择一个DXF文件</label>
      <input
        id="dxf"
        type="file"
        accept=".dxf"
        name="file"
        @change="onFileSelected"
      />
      <div class="progress progress-striped" style="width: 300px">
        <div
          id="file-progress-bar"
          class="progress-bar progress-bar-success"
          role="progressbar"
          style="width: 0"
        ></div>
      </div>
      <div id="file-description" class="help-block"></div>
    </div>
    <canvas id="box"></canvas>
  </div>
</template>

<script>
/* eslint-disable */
import DxfParser from "dxf-parser";
import { Leafer, Line } from "leafer-ui";
import "@leafer-in/viewport"; // 导入视口插件

export default {
  name: "HomeView",
  components: {},
  data() {
    return {
      leafer: null,
    };
  },
  mounted() {
    const leafer = new Leafer({
      view: "box",
      type: "design",
      wheel: { zoomMode: true },
    });

    this.leafer = leafer;
  },
  methods: {
    onFileSelected(evt) {
      var file = evt.target.files[0];
      var reader = new FileReader();
      reader.onloadend = this.onSuccess;
      reader.onerror = this.errorHandler;
      reader.readAsText(file);
    },
    errorHandler(evt) {
      switch (evt.target.error.code) {
        case evt.target.error.NOT_FOUND_ERR:
          alert("File Not Found!");
          break;
        case evt.target.error.NOT_READABLE_ERR:
          alert("File is not readable");
          break;
        case evt.target.error.ABORT_ERR:
          break;
        default:
          alert("An error occurred reading this file.");
      }
    },
    onSuccess(evt) {
      this.dxfLoading = true;
      var fileReader = evt.target;
      if (fileReader.error) return console.log("error onloadend!?");
      var parser = new DxfParser();
      var dxf = parser.parseSync(fileReader.result);
      console.log(dxf);
      let entities = dxf.entities;
      for (let ent of entities) {
        switch (ent.type) {
          case "LINE":
            console.log(ent);
            const line = new Line({
              points: [
                ent.vertices[0].x,
                ent.vertices[0].y,
                ent.vertices[1].x,
                ent.vertices[1].y,
              ],
              strokeWidth: 1,
              stroke: "#32cd79",
              strokeWidthFixed: "zoom-in",
            });
            this.leafer.add(line);
            break;
        }
      }
    },
  },
};
</script>
<style scoped>
.home {
  width: 90vw;
  height: 70vh;
}

#box {
  border: 1px solid #c56565;
}
</style>
